package com.ailot.cloud.base.security.exception;


import com.ailot.cloud.base.common.dto.Result;
import com.ailot.cloud.base.common.exception.GlobalExceptionHandlerResolver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 处理security异常的通用处理器
 */
@Slf4j
@RestControllerAdvice
@AutoConfigureBefore(GlobalExceptionHandlerResolver.class)
// 在全局之前
@Order(Ordered.LOWEST_PRECEDENCE - 10)
public class SecurityExceptionHandler {


    /**
     * 拒绝异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public Result<?> handleGlobalException(AccessDeniedException e) {
        log.warn("权限不足 ex={}", e.getMessage());
        // 多为接口 hasAuthority 等权限不足
        return Result.fail("权限不足");
    }
}
